package com.smzd.utils.freemarker;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerHelper {
	private static final Log logger = LogFactory.getLog(FreeMarkerHelper.class);
	private static final Configuration cfg;
	static {
		cfg = new Configuration();
		cfg.setClassicCompatible(true);
	}

	private FreeMarkerConfigurer freeMarkerConfigurer;

	public FreeMarkerConfigurer getFreeMarkerConfigurer() {
		return freeMarkerConfigurer;
	}

	public void setFreeMarkerConfigurer(
			FreeMarkerConfigurer freeMarkerConfigurer) {
		this.freeMarkerConfigurer = freeMarkerConfigurer;
	}

	private static int id;

	private static int getId() {
		return id++;
	}

	public static String render(String template, Map<String, ?> root)
			throws IOException, TemplateException {
		String content = null;
		Reader reader = new StringReader(template);
		Writer writer = new StringWriter();
		Template t = new Template("temp_" + getId(), reader, cfg);
		t.process(root, writer);
		content = writer.toString();

		return content;
	}

	public String renderByView(String view, Map<String, ?> root)
			throws IOException, TemplateException {
		try {
			Template tpl = freeMarkerConfigurer.getConfiguration().getTemplate(
					view);
			if (tpl == null) {
				return render(view, root);
			}
			return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, root);
		} catch (IOException e) {
			logger.error("IO异常:"+view);
		} catch (TemplateException e) {
			logger.error("模板异常:"+view);
		}
		return render(view, root);
	}
}
